import socket

from flask import Blueprint

from app import db

user_bp = Blueprint('user1', __name__)

from flask import request
from werkzeug.security import generate_password_hash, check_password_hash
from app.utils import response


@user_bp.route('/register', methods=['POST'])
def register():
    from . import db  # 导入数据库实例
    from .models import User  # 导入 User 模型
    user_name = request.args.get('user_name')
    password = request.args.get('password')
    print(user_name, password)
    # 检查用户名或邮箱是否已存在
    if User.query.filter_by(user_name=user_name).first():
        # or User.query.filter_by(email=email).first() or User.query.filter_by(phone=phone).first()):
        return response(400)

    # 加密密码
    hashed_password = generate_password_hash(password, method='pbkdf2')

    avatar_url = 'https://api.multiavatar.com/' + user_name + '.svg'
    # 获取服务器的主机名
    host_name = socket.gethostname()
    # 获取服务器的IP地址
    host_ip = socket.gethostbyname(host_name)
    # 创建新用户实例
    new_user = User(
        user_name=user_name,
        password=hashed_password,
        # phone=phone,
        # email=email,
        ip=host_ip,
        avatar_url=avatar_url
    )

    # 将新用户添加到数据库
    db.session.add(new_user)
    db.session.commit()

    return response(200)


@user_bp.route('/login', methods=['POST'])
def login():
    # 从请求体中获取用户名和密码
    from .models import User  # 导入 User 模型
    user_name = request.args.get('user_name')
    password = request.args.get('password')
    print(user_name, password)
    if not user_name or not password:
        print(3)
        return response(400)

    user = User.query.filter_by(user_name=user_name).first()

    data = {
        'user_name': user_name,
        'user_id': user.user_id,
        'avatar_url': user.avatar_url
    }
    print(user.user_id)
    user.ip = request.remote_addr
    db.session.commit()
    if user and check_password_hash(user.password, password):
        return response(200, data)
    else:
        return response(400)
